import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///
/// Author: chengzan
/// Date: 2020-6-8
/// Describe: 单个选择picker
///

class SinglePickerWidget extends StatefulWidget {
  final List<Map> values;
  final value;
  final double itemHeight;
  final double height=120;
  final double width=200;
  final String unit;
  final Function onChanged;
  final Color backgroundColor;

  SinglePickerWidget(
      {super.key,
        required this.values,
          required this.value,
        required this.onChanged,
        required this.unit,
        this.itemHeight = 37.5,
        this.backgroundColor = const Color(0x00ffffff),
      })
      ;
  @override
  _SinglePickerWidgetState createState() => _SinglePickerWidgetState();
}

class _SinglePickerWidgetState extends State<SinglePickerWidget> {
  int _selectedColorIndex = 0;
  late FixedExtentScrollController scrollController;
  var values;
  var value;

  //设置防抖周期为300毫秒
  Duration durationTime = Duration(milliseconds: 300);
  late Timer timer;

  @override
  void initState() {
    super.initState();
    timer=Timer(durationTime, () {

    });
    values = widget.values;
    value = widget.value;
    getDefaultValue();
    scrollController =
        FixedExtentScrollController(initialItem: _selectedColorIndex);
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
    timer?.cancel();
  }

  // 获取默认选择值
  getDefaultValue() {
    // 查找要选择的默认值
    for (var i = 0; i < values.length; i++) {
      if (values[i]["value"] == value) {
        setState(() {
          _selectedColorIndex = i;
        });
        break;
      }
    }
  }

  // 触发值改变
  void _changed(index) {
    if(timer!=null)
    timer?.cancel();
    timer = Timer(durationTime, () {
      // 触发回调函数
      widget.onChanged(values[index]["value"]);
    });
  }

  Widget _buildColorPicker(BuildContext context) {
    return Container(
      height: widget.height,
      color: Colors.transparent,
      child: Stack(
        alignment: Alignment.center,
        children: [
          widget.unit != null
              ? Positioned(
            top: widget.height / 2 - (widget.itemHeight / 2)+2,
            left: widget.width / 2 + 30.0,
            child: Container(
              alignment: Alignment.center,
              height: widget.itemHeight,
              child: Text(
                widget.unit,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16.0,
                  height: 1.5,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          )
              : Offstage(
            offstage: true,
          ),
          CupertinoPicker(
            magnification: 1.0, // 整体放大率
            looping: true,
            scrollController:
            scrollController, // 用于读取和控制当前项的FixedxtentScrollController
            itemExtent: widget.itemHeight, // 所有子节点 统一高度
            useMagnifier: true, // 是否使用放大效果
            backgroundColor: Colors.transparent,
            onSelectedItemChanged: (int index) {
              // 当正中间选项改变时的回调
              if (mounted) {
                print('index--------------$index');
                _changed(index);
              }
            },
            children: List<Widget>.generate(values.length, (int index) {
              return Container(
                alignment: Alignment.center,
                height: widget.itemHeight,
                child: Text(
                  values[index]["label"],
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 25.0,
                    height: 1.2,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              );
            }),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      height: widget.height,
      width: widget.width,
      //child: CupertinoPageScaffold(
        child: Container(

          child: ListView(
            padding: EdgeInsets.all(0),
            children: <Widget>[
              _buildColorPicker(context),
            ],
          ),
        ),

    );
  }
}

